package com.atguigu.crowd.mvc.handler;

import com.atguigu.crowd.entity.Menu;
import com.atguigu.crowd.service.api.MenuService;
import com.atguigu.crowd.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/authority/menu")
public class MenuHandler {

    @Autowired
    private MenuService menuService;

    @RequestMapping("/list")
    public String getMenuPage() {
        return "menu-page";
    }

    @ResponseBody
    @RequestMapping("/tree")
    private ResultEntity<Menu> getWholeMenuTree() {

        List<Menu> menuList = menuService.getAll();
        Menu root = null;
        Map<Integer, Menu> menuMap = new HashMap<>();

        for (Menu menu : menuList) {
            menuMap.put(menu.getId(), menu);
        }

        for (Menu menu : menuList) {
            Integer pid = menu.getPid();

            if (pid == null) {
                root = menu;
                continue;
            }

            Menu parent = menuMap.get(pid);
            parent.getChildren().add(menu);
        }
        return ResultEntity.successWithData(root);
    }

    @ResponseBody
    @RequestMapping("/add")
    public ResultEntity<String> addMenu(@RequestBody Menu menu) {
        menuService.saveMenu(menu);
        return ResultEntity.successWithoutData();
    }

    @ResponseBody
    @RequestMapping("/get/{menuId}")
    public ResultEntity<Menu> getMenuById(@PathVariable("menuId") Integer menuId) {
        Menu meun = menuService.getMenuById(menuId);
        return ResultEntity.successWithData(meun);
    }

    @ResponseBody
    @RequestMapping("/update")
    public ResultEntity<String> updateMenu(@RequestBody Menu menu) {
        menuService.updateMenu(menu);
        return ResultEntity.successWithoutData();
    }

    @ResponseBody
    @RequestMapping("/delete")
    public ResultEntity<String> removeMenu(@RequestParam("id") Integer menuId) {
        menuService.removeMenu(menuId);
        return ResultEntity.successWithoutData();
    }


}
